#!/usr/bin/env node

const https   = require('https'),
      log     = console.log,
      cheerio = require('cheerio'),
      //url     = require('url'),
      addr    = 'https://maoyan.com/films?showType=3',
      //addr    = 'https://maoyan.com/films',
      http    = require('http'),
      fs      = require('fs');

let html = fs.readFileSync('./index.html').toString('utf-8');
let movieList = [];

/*
let opt  = url.parse(addr);
opt.headers = {
  //'user-agent' : 'curl/7.29.0'
  //'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36'
  'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1',
  'Cookie': 'UM_distinctid=174ba7f6b31567-09f4e06f44d888-3a614f0b-e1000-174ba7f6b3248b; csrftoken=6Hbznlm9qzGwAsnP9gpa1tEYP3m41I8C9XMyAFaPmlfWsJCn3n4LR3lXX95u89WY; sessionid=8x5p4pxtqs6pivbw5z71rt8bcy2p067r; CNZZDATA1256646432=322145187-1569307251-null%7C1604447367'
};
*/

https.get(addr,(res) => {
  let data = '';

  res.on('data',(chunk) => data += chunk);

  res.on('end',() => {
    let $      = cheerio.load(data);
    let list   = $('body').find('dd');
    let movies = $('body').find('div.channel-detail>a');
    let ranges = $('body').find('div.channel-detail-orange');

    for(let i=0;i<list.length;i++){

      let movieId    = $(movies[i]).attr('data-val');
      let movieName  = $(movies[i]).text(); 
      let movieRange = $(ranges[i]).text();
      movieList.push({
        movieId : movieId.slice(9,movieId.length-1),
        movieName : movieName,
        movieRange : movieRange
      });
    }
    log(movieList);
  });
});

http.createServer((req,res) => {
  if(req.url === '/'){
    res.writeHead(200,{
      'Content-Type':'text/html',
      'Content-Length':Buffer.byteLength(html)    
    });
    res.end(html);
  }else if(req.url === '/getlist'){
    res.statusCode = 200;
    res.setHeader('Content-Type','text/html');
    res.end(JSON.stringify(movieList));
  }else{
    res.statusCode = 404;
    res.setHeader('Content-Type','text/html');
    res.end('<h1>Not Found!</h1>');
  }
    return;
}).listen(8080);
